<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryRef" :inline="true" :model="queryParams" label-width="68px">
      <el-form-item label="名称" prop="planName">
        <el-input v-model="queryParams.planName" clearable placeholder="请输入名称" @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" clearable placeholder="请选择" style="width: 240px">
          <el-option v-for="dict in nursing_plan_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button icon="Plus" plain type="primary" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="planList">
      <el-table-column label="序号" type="index" width="50"/>
      <el-table-column align="center" label="名称" prop="planName"/>
      <el-table-column align="center" label="状态" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作" width="280">
        <template #default="scope">
          <el-button :class="scope.row.count ? 'disabled' : ''" icon="Edit" link type="primary"
                     @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button :class="scope.row.count ? 'disabled' : ''" icon="Delete" link type="primary"
                     @click="handleDelete(scope.row)">删除
          </el-button>
          <el-button icon="ZoomIn" link type="primary" @click="handleLook(scope.row)">查看</el-button>
          <el-button :icon="scope.row.status === 0 ? 'Unlock' : 'lock'" link type="primary"
                     @click="handleEnable(scope.row)">{{ scope.row.status === 1 ? '禁用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                :total="total" @pagination="getNursingPlanList"/>

    <el-dialog v-model="dialogVisible" title="新增护理计划" width="840" @close="cancel()">
      <el-form ref="planRef" :model="formData" :rules="rules" label-width="120px">
        <el-row gutter="10">
          <el-col :span="24" class="elcolFlex">
            <el-form-item label="护理计划名称：" prop="planName">
              <el-input v-model="formData.planName" :disabled="isLook"></el-input>
            </el-form-item>
            <el-form-item label="状态：" prop="status">
              <el-radio-group v-model="formData.status" :disabled="isLook">
                <el-radio v-for="dict in nursing_plan_status" :key="dict.value" :label="dict.value" :value="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="排序：" prop="sortNo">
              <el-input-number v-model="formData.sortNo" :decimal-places="0" :disabled="isLook" :max="999999" :min="0"
                               large-number @blur="textBlurNo" @change="textBlurNo"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="护理项目：" prop="price">
          <div class="info family">
            <div class="tableHead">
              <div>护理项目名称</div>
              <div>期望服务时间</div>
              <div>执行周期</div>
              <div>执行频次(次)</div>
              <div v-if="!isLook">操作</div>
            </div>
            <div class="tableBody">
              <div v-for="(item, index) in nursingPlanList" :key="index" class="tableColumn">
                <div class="column">
                  <el-select v-model="item.projectId" :disabled="isLook" placeholder="请选择">
                    <el-option v-for="item in nursingProjectOptions" :key="item.value" :label="item.label"
                               :value="item.value"></el-option>
                  </el-select>
                </div>
                <div class="column">
                  <el-time-picker v-model="item.executeTime" :disabled="isLook" :style="{ width: '100%' }" clearable
                                  format="HH:mm:ss" placeholder="请选择时间选择"
                                  value-format="HH:mm:ss"></el-time-picker>
                </div>
                <div class="column">
                  <el-select v-model="item.executeCycle" :disabled="isLook" placeholder="请选择">
                    <el-option v-for="item in executeCycleOptions" :key="item.value" :label="item.label"
                               :value="item.value"></el-option>
                  </el-select>
                </div>
                <div class="column">
                  <el-input-number v-model="item.executeFrequency" :controls="false" :disabled="isLook" :max="7"
                                   :min="1"/>
                </div>
                <div v-if="!isLook" class="column">
                  <el-icon v-if="nursingPlanList.length > 1" class="delect" @click="handleRowDel(item, index)">
                    <Minus/>
                  </el-icon>
                  <el-icon class="add" @click="handleRowAdd">
                    <Plus/>
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <div v-if="!isLook" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel()">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script name="Plan" setup>
import {
  addNursingPlan,
  delNursingPlan,
  getNursingPlan,
  listNursingPlan,
  planStatus,
  updateNursingPlan,
} from '@/api/nursing/plan';
import {getAllProjects} from '@/api/nursing/project';
import {onMounted} from 'vue';

const {proxy} = getCurrentInstance();
const {nursing_plan_status} = proxy.useDict('nursing_plan_status');
const queryRef = ref();
const planList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref('');
const dialogVisible = ref(false);
const nursingProjectOptions = ref([]);
const isLook = ref(false);
const formData = ref({
  status: '1',
  sortNo: 1,
});

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  planName: null,
  status: null,
});

const rules = ref({
  planName: [
    {
      required: true,
      message: '护理计划名称为空，请输入护理计划名称',
      trigger: 'blur',
    },
  ],
  status: [
    {
      required: true,
      message: '状态为空，请选择状态',
      trigger: 'change',
    },
  ],
  sortNo: [
    {
      required: true,
      message: '排序为空，请选择排序',
      trigger: 'change',
    },
  ],
});

const executeCycleOptions = ref([
  {label: '天', value: '0'},
  {label: '周', value: '1'},
  {label: '月', value: '2'},
]);

onMounted(() => {
  getAllProjectList();
});

//查询所有护理项目
const getAllProjectList = () => {
  getAllProjects().then((res) => {
    nursingProjectOptions.value = res.data;
  });
};

const nursingPlanList = ref([
  {
    projectId: '',
    executeTime: '',
    executeCycle: '',
    executeFrequency: '',
  },
]);

const handleRowAdd = () => {
  const obj = {
    projectId: '',
    executeTime: '',
    executeCycle: '',
    executeFrequency: '',
  };
  nursingPlanList.value.push(obj);
};

//删除行数据
const handleRowDel = (item, index) => {
  if (nursingPlanList.value.length === 1) return;
  nursingPlanList.value.splice(index, 1);
};

/** 查询护理计划列表 */
function getNursingPlanList() {
  loading.value = true;
  listNursingPlan(queryParams.value).then((response) => {
    planList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  dialogVisible.value = false;
  isLook.value = false;
  reset();
}

// 表单重置
function reset() {
  formData.value = {
    planName: null,
    status: '1',
    sortNo: 1,
  };
  nursingPlanList.value = [
    {
      projectId: '',
      executeTime: '',
      executeCycle: '',
      executeFrequency: '1',
    },
  ];
  console.log(nursingPlanList.value);
  // proxy.resetForm('planRef');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getNursingPlanList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  dialogVisible.value = true;
  title.value = '添加护理计划';
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const _id = row.id || ids.value;
  getDetails(_id);
}

// 获取详情
const getDetails = (id) => {
  getNursingPlan(id).then((response) => {
    formData.value = response.data;
    formData.value.status = String(formData.value.status);
    nursingPlanList.value = formData.value.projectPlans;
    dialogVisible.value = true;
    title.value = '修改护理计划';
  });
};

/** 提交按钮 */
function submitForm() {
  if (hasDuplicateIds(nursingPlanList.value)) {
    proxy.$modal.msgError('请勿选择重复的护理项目');
    return;
  }
  formData.value['projectPlans'] = nursingPlanList.value;
  console.log(formData.value);
  proxy.$refs['planRef'].validate((valid) => {
    if (valid) {
      if (formData.value.id != null) {
        updateNursingPlan(formData.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功');
          cancel();
          getNursingPlanList();
        });
      } else {
        addNursingPlan(formData.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功');
          cancel();
          getNursingPlanList();
        });
      }
    }
  });
}

//判断数组中的对象的id是否有相同的
function hasDuplicateIds(objectsArray) {
  if (!Array.isArray(objectsArray) || objectsArray.length === 0) {
    return false;
  }
  const idSet = new Set();
  for (const obj of objectsArray) {
    if (obj.projectId !== undefined) {
      idSet.add(obj.projectId);
    }
  }
  return idSet.size !== objectsArray.length;
}

/** 启用/禁用 */
const handleEnable = async (row) => {
  try {
    const status = row.status;
    const info = status === 0 ? '启用' : '禁用';
    const confirmMessage = `是否确认${info}护理项目的数据项？`;
    if (await proxy.$modal.confirm(confirmMessage)) {
      const param = {
        id: row.id,
        status: status === 0 ? 1 : 0,
      };
      await planStatus(param);
      getNursingPlanList();
      proxy.$modal.msgSuccess(`${info}成功`);
    }
  } catch (error) {
    console.error('操作失败，请重试或联系管理员。');
  }
};

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
      .confirm('是否确认删除护理计划编号为"' + _ids + '"的数据项？')
      .then(function () {
        return delNursingPlan(_ids);
      })
      .then(() => {
        getNursingPlanList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .catch(() => {
      });
}

//监听排序
const textBlurNo = () => {
  const data = formData.value.sortNo;
  if (data <= 1) {
    formData.value.sortNo = 1;
  }
  if (data > 99999999) {
    formData.value.sortNo = 99999999;
  }
};

// 查看
const handleLook = (row) => {
  isLook.value = true;
  dialogVisible.value = true;
  getDetails(row.id);
};
getNursingPlanList();
</script>

<style lang="scss" src="./index.scss"></style>
